package com.itelite.handler;

import com.itelite.common.info.Result;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.management.ServiceNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 31-05-2021-18:02
 **/
@EnableWebMvc
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private final static String ERROR_URL="访问的URL:";
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestPartException.class)
    public Result handleMissingServletRequestPartException(HttpServletRequest request,MissingServletRequestPartException e) {
        String msg = "缺少请求参数!";
        log.error(msg);
        return Result.failure(msg);
    }
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(IOException.class)
    public Result handleFileNotFoundException(HttpServletRequest request,IOException e) {
        String msg = "文件读写失败!";
        log.info(msg);
        return Result.failure(msg);
    }

//    AccessDeniedException
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(HttpServletRequest request,MissingServletRequestParameterException e) {
        String msg = "缺少请求参数！"+ERROR_URL+request.getRequestURI();
        log.info(msg);
        return Result.failure(msg);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(HttpServletRequest request, AccessDeniedException e) {
        String msg = "访问权限不足!"+ERROR_URL+request.getRequestURI();
//        log.info(request.getRemoteHost()+msg);
        return Result.failure(HttpStatus.FORBIDDEN,msg);
    }
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result handleHttpMessageNotReadableException(HttpServletRequest request,HttpMessageNotReadableException e) {
        String msg = "参数解析失败！"+ERROR_URL+request.getRequestURI();
//        log.error(msg,e);
        return Result.failure(msg);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public Result handleMethodArgumentTypeMismatchException(HttpServletRequest request,MethodArgumentTypeMismatchException e) {
        String msg = "参数解析失败！"+ERROR_URL+request.getRequestURI();
        return Result.failure(msg);
    }
    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = ValidateHandler.catchErrors(e);
//        log.error(msg);
        return Result.failure(msg);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        String msg = ValidateHandler.catchErrors(e);
//        log.error(msg);
        return Result.failure(msg);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleServiceException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String msg = violations.iterator().next().getMessage();
        log.error(msg);
        return Result.failure(msg);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(HttpServletRequest request,ValidationException e) {
        String msg = "参数验证失败!"+ERROR_URL+request.getRequestURI();
//        log.error(msg);
        return Result.failure(msg);
    }



    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpServletRequest request,HttpRequestMethodNotSupportedException e) {
        String msg = "不支持当前请求方法！"+ERROR_URL+request.getRequestURI();
//        log.error(msg);
        return Result.failure(msg);
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result handleHttpMediaTypeNotSupportedException(HttpServletRequest request, Exception e) {
        String msg = "不支持当前媒体类型！"+ERROR_URL+request.getRequestURI();
//        log.error(msg);
        return Result.failure(msg);
    }
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(SignatureException.class)
    public Result handleSignatureException(SignatureException e){
//        log.error("TOKEN异常");
        return Result.failure("TOKEN异常");
    }
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataAccessException.class)
    public Result handleDataAccessException(HttpServletRequest request,DataAccessException e) {
        String msg = "服务器内部异常！"+ERROR_URL+request.getRequestURI();
//        log.error(msg,e);
        return Result.failure(msg);
    }

    /**
     * 422 - UNPROCESSABLE_ENTITY
     */
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result handleMaxUploadSizeExceededException(Exception e) {
        String msg = "所上传文件大小超过最大限制，上传失败！";
//        log.error(msg);
        return Result.failure(msg);
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ServiceNotFoundException.class)
    public Result handleServiceException(ServiceNotFoundException e) {
        String msg = "服务未找到";
//        log.error(msg,e);
        return Result.failure(msg);
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        String msg = "服务器繁忙";
        log.error(msg,e);
        return Result.failure(msg);
    }
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handleException(RuntimeException e) {
        String msg = "服务器繁忙,请重试";
        log.error(msg,e);
        return Result.failure(msg);
    }
    private String handleBindingResult(BindingResult result) {
        if (result.hasErrors()) {
            final List<FieldError> fieldErrors = result.getFieldErrors();
            return fieldErrors.iterator().next().getDefaultMessage();
        }
        return null;
    }
}
